package com.colter.project.sample.thread.part06.test1;

import java.util.concurrent.PriorityBlockingQueue;

//按优先级排序的阻塞式线程 PriorityBlockingQueue
public class Test4 {
	public static void main(String[] args) {
		PriorityBlockingQueue<Event> list = new PriorityBlockingQueue<>();
		Thread[] taskThreads = new Thread[5];
		for (int i = 0; i < taskThreads.length; i++) {
			Task task = new Task(i, list);
			taskThreads[i] = new Thread(task);
		}

		for (int i = 0; i < taskThreads.length; i++) {
			taskThreads[i].start();
		}

		for (int i = 0; i < taskThreads.length; i++) {
			try {
				taskThreads[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("Main:Queue: Size:" + list.size());

		for (int i = 0; i < taskThreads.length * 100; i++) {
			Event event = list.poll();
			System.out.println("Main:Event: Poll:" + event);
		}

		System.out.println("Main:End:Size:" + list.size());
	}
}

class Event implements Comparable<Event> {
	private int thread;
	private int priority;

	public int getThread() {
		return thread;
	}

	public void setThread(int thread) {
		this.thread = thread;
	}

	public int getPriority() {
		return priority;
	}

	public void setPriority(int priority) {
		this.priority = priority;
	}

	public Event(int thread, int priority) {
		super();
		this.thread = thread;
		this.priority = priority;
	}

	@Override
	public String toString() {
		return "Event [thread=" + thread + ", priority=" + priority + "]";
	}

	@Override
	public int compareTo(Event o) {
		if (this.priority > o.priority) {
			return -1;
		} else if (this.priority < o.priority) {
			return 1;
		} else {
			if (this.thread > o.thread) {
				return -1;
			} else if (this.thread < o.thread) {
				return 1;
			}
			return 0;
		}

	}
}

class Task implements Runnable {
	private int id;
	private PriorityBlockingQueue<Event> list;

	public Task(int id, PriorityBlockingQueue<Event> list) {
		super();
		this.id = id;
		this.list = list;
	}

	@Override
	public void run() {
		for (int i = 0; i < 100; i++) {
			Event e = new Event(i, i);
			list.add(e);
		}
	}

}
